<?php
/**
 * 企业用户管理
 * gemj
 */
if(!defined("SYSTEM_TIME")){
	define("SYSTEM_TIME", isset ( $_SERVER ['REQUEST_TIME'] ) ? $_SERVER ['REQUEST_TIME'] : time ());
}
class Libs_EUser
{
	private static $loginKey = '!1@2#3%4';
	private static $loginCookieName = 'resume_auth';
	private static $adminLoginCookieName = 'resume_auth_eadmin';
	/**
	 * 执行用户登录
	 * @param array $paramArr
	 * @return array
	 */
	public static function userLogin($paramArr){
		$userName = trim($paramArr['username']);
		$userPwd  = $paramArr['password'];
		list($id, $username ) = enterprise_user_login($userName, $userPwd);
		$msg = '';
		if($id > 0) {
			$msg =  '登录成功';
		} else {
			$msg =  '用户名或者密码错误!';
		}
		return array('id'=>$id,'msg'=>$msg);
	}


	public static function enterprise_user_login($name, $userpw){
		$name = strval(trim($name));
		$userpw = md5(trim($userpw));

		$db = Db_Resume::instance();
		$sql = "Select id, name from e_user where name='{$name}' and passwd='{$userpw}' limit 1";
		$row = $db->getRow($sql);

		return $row;
	}


	/**
	 * 获取用户的基本信息
	 * @param array $paramArr
	 * @return array
	 */
	public static function getUserInfo($paramArr){
		$nameOrId = $paramArr['nameOrId'];
		$flag     = $paramArr['flag'] ? 1:0; //1:使用用户 ID获取 0:(默认值) 使用用户名获取
		$rtnArr   = array();
		if($data = uc_get_user($nameOrId,$flag)) {
			$rtnArr = array(
					'id'       => $data[0],
					'name'  => $data[1],
					'email'     => $data[2],
				       );
		}
		return $rtnArr;
	}
	/**
	 * 编辑用户信息
	 * @param <type> $paramArr
	 * @return <type>
	 */
	public static function editUserInfo($paramArr){
		if (is_array($paramArr)) {
			$option = $paramArr;
			$options = array(
					'name' => '',
					'oldpw'    => '',
					'newpw'    => '', //新密码，如不修改为空
					'email'    => '', //Email，如不修改为空
					'ignoreoldpw'   => 0, //1:忽略，更改资料不需要验证密码
					'questionid'    => 0, //1:忽略，更改资料不需要验证密码
					'answer'        => '', //1:忽略，更改资料不需要验证密码
					);
			$options = array_merge($options, $paramArr);
			extract($options);
		}

		$ucresult = uc_user_edit($username, $oldpw, $newpw, $email,$ignoreoldpw);//,$questionid,$answer
		$msg = '';
		if($ucresult == -1) { //1:更新成功 0:没有做任何修改 -7:没有做任何修改 -8:该用户受保护无权限更改
			$msg =  '旧密码不正确';
		} elseif($ucresult == -4) {
			$msg =  'Email 格式有误';
		} elseif($ucresult == -5) {
			$msg =  'Email 不允许注册';
		} elseif($ucresult == -6) {
			$msg =  '该 Email 已经被注册';
		}

		return array('flag'=>$ucresult,'msg'=>$msg);
	}



	/**
	 *
	 * 登录，并且得到其他应用同步登录的js代码，这个代码必须输出，才能完成其他应用的同步登录
	 * @param <type> $paramArr
	 * @return <type>
	 */
	public static function synLogin($paramArr){
		if (is_array($paramArr)) {
			$option = $paramArr;
			$options = array(
					'username' => '',
					'password'    => '',
					);
			$options = array_merge($options, $paramArr);
			extract($options);
		}

		list($uid, $username, $password, $email) = uc_user_login($username, $password);
		$msg = '';
		$synJsHtml = '';
		if($uid > 0) {
			$msg = '登录成功';
			$synJsHtml = uc_user_synlogin($uid);
		} elseif($uid == -1) {
			$msg = '用户不存在';
		} elseif($uid == -2) {
			$msg = '密码错误';
		} else {
			$msg = '未定义';
		}
		return array('id'=>$uid,'msg'=>$msg,'synJsHtml'=>$synJsHtml);
	}


	/**
	 *
	 * 退出，并且得到其他应用同步退出的js代码，这个代码必须输出，才能完成其他应用的同步退出
	 * @param <type> $paramArr
	 * @return <type>
	 */
	public static function synLogOut(){

		$synJsHtml = uc_user_synlogout();
		return $synJsHtml;
	}
	//检查mail合法性
	public static function checkMail($mail){
		$flag = uc_user_checkemail($mail);
		$msg = '';
		if($flag <= 0) {
			if($flag == -4) {
				$msg =  'Email 格式有误';
			} elseif($flag == -5) {
				$msg =  '该Email 不允许注册';
			} elseif($flag == - 6) {
				$msg =  '该Email 已经被注册';
			}
		} else {
			$msg =  '成功';
		}
		return array('flag'=>$flag,'msg'=>$msg);
	}

	//检查用户名合法性
	public static function checkUserName($uName){
		$flag = uc_user_checkname($uName);
		$msg = '';
		if($flag <= 0) {
			if($flag == -1) {
				$msg =  '用户名不合法';
			} elseif($flag == -2) {
				$msg =  '包含要允许注册的词语';
			} elseif($flag == - 3) {
				$msg =  '用户名已经存在';
			}
		} else {
			$msg =  '成功';
		}
		return array('flag'=>$flag,'msg'=>$msg);
	}
	/**
	 *
	 * 设置登录状态
	 */
	public static function setLoginStatus($paramArr){
		if (is_array($paramArr)) {
			$options = array(
					'id'      => '',
					'name' => '',
					'passwd' => '',
					'subid' => '',
					'life'     => '',
					);
			$options = array_merge($options, $paramArr);
			extract($options);
		}
		$id  = (int)$id;
		$life = (int)$life;
		$life = $life ? $life + SYSTEM_TIME : 0 ;
		$uStr = self::authcode("{$id}\t{$name}\t{$passwd}\t{$subid}","ENCODE",self::$loginKey);

		setcookie(self::$loginCookieName, $uStr,$life, '/');

	}
	/**
	 * 用户退出
	 */
	public static function clearLoginStatus($input,$output){
		$life = SYSTEM_TIME - 100000;
		setcookie(self::$adminLoginCookieName, ' ',$life, '/');
	}
	/**
	 * 进入登录界面
	 */
	public static function goToLoginPage($input,$output){
		header("Location: ?c=Login");
		exit;
	}

	public static function getLoginStatus($input,$output){
		$authStr = trim($input->cookie(self::$adminLoginCookieName));
		$authArr = array();
		if($authStr){
			$authArrStr = self::authcode($authStr,"DECODE",self::$loginKey);
			$authArr = explode("\t",$authArrStr);
		}
		return $authArr;
	}
	//验证是否登录
	public static function checkLogin($input,$output){

		$loginArr = self::getLoginStatus($input,$output);

		$id = 0;
		if(is_array($loginArr)){
			$id = isset($loginArr[0]) ? (int)$loginArr[0] : 0;

		}
		if(!$id && $input->jumpLogin){
			self::goToLoginPage($input,$output);
		}

		return array(
				'id'      => $id ,
				'name' => isset($loginArr[1]) ? trim($loginArr[1]) : '',
				'passwd' => isset($loginArr[2]) ? trim($loginArr[2]) : '',
				'subid' => isset($loginArr[3]) ? trim($loginArr[3]) : '',
			    );
	}
	/**
	 *
	 * 加密解密函数
	 */
	public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
		$ckey_length = 4;

		$key = md5($key ? $key : UC_KEY);
		$keya = md5(substr($key, 0, 16));
		$keyb = md5(substr($key, 16, 16));
		$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

		$cryptkey = $keya.md5($keya.$keyc);
		$key_length = strlen($cryptkey);

		$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
		$string_length = strlen($string);

		$result = '';
		$box = range(0, 255);

		$rndkey = array();
		for($i = 0; $i <= 255; $i++) {
			$rndkey[$i] = ord($cryptkey[$i % $key_length]);
		}

		for($j = $i = 0; $i < 256; $i++) {
			$j = ($j + $box[$i] + $rndkey[$i]) % 256;
			$tmp = $box[$i];
			$box[$i] = $box[$j];
			$box[$j] = $tmp;
		}

		for($a = $j = $i = 0; $i < $string_length; $i++) {
			$a = ($a + 1) % 256;
			$j = ($j + $box[$a]) % 256;
			$tmp = $box[$a];
			$box[$a] = $box[$j];
			$box[$j] = $tmp;
			$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}

		if($operation == 'DECODE') {
			if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
				return substr($result, 26);
			} else {
				return '';
			}
		} else {
			return $keyc.str_replace('=', '', base64_encode($result));
		}

	}

	public static function uploadAvatar($paramArr){
		if (is_array($paramArr)) {
			$options = array(
					'uid'      => '',
					'type'     => 1,//1  真是，2 虚拟
					'getHtml'  => true,//是否获得html，flase返回flash数组
					);
			$options = array_merge($options, $paramArr);
			extract($options);
		}
		$uid  = (int)$uid;
		$type = (int)$type;
		return uc_avatar($uid, $type == 1 ? 'real' : 'virtual', $getHtml);
	}

	//返回头像
	public static function getAvatar($paramArr){
		if (is_array($paramArr)) {
			$options = array(
					'uid'      => '',
					'type'     => 1,//1  真是，2 虚拟
					'size'    => 'big',//big middle small
					);
			$options = array_merge($options, $paramArr);
			extract($options);
		}
		$uid  = (int)$uid;
		if(!$uid) return '';
		$type = (int)$type;
		$type = $type == 1 ? 'real' : 'virtual';
		return UC_API . "/avatar.php?uid={$uid}&type={$type}&size={$size}";
	}

	// 用户退出
	public static function clearEuserLoginStatus($input,$output){
		$life = SYSTEM_TIME - 100000;
		setcookie(self::$loginCookieName, ' ',$life, '/');
	}
	//获得后台登录的数据
	public static function getAdminLoginInfo(ME_Request $input, ME_Response $output){

		$authStr = trim($input->cookie(self::$adminLoginCookieName));
		$authArr = array();
		if($authStr){
			$authArrStr = self::authcode($authStr,"DECODE",self::$loginKey);
			$authArr = explode("\t",$authArrStr);
		}
		if(empty($authArr) && $input->doJump){
			echo '<script>window.location.href="index.php?c=Login";top.window.location.href="index.php?c=Login";</script>';
			exit;
		}
		return $authArr;
	}
	public static function checkAdminLogin($username,$passwd,$utype,$firmTag){
		if(empty($username) || empty($passwd)){
			return false;
		}
		$life = time()+3600*24;
		$db = Db_Resume::instance();

		//manage login
		if(1 == $utype){
			$sql = "SELECT id,name,passwd FROM e_user WHERE name='$username'";
		} else { // normal login
			$sql = "SELECT id,name,passwd,firm_id FROM `e_sub_user` WHERE status=0 and name='{$username}' and firm_tag='{$firmTag}'";
		}
		//进行赋值操作
		$resm = $db->getRow($sql);
		$dbpass = $resm['passwd'];
		if(md5($passwd) == $dbpass){
			//manager with subuserid X
			if(1 == $utype){
				$setStr = "{$resm['id']}\t{$username}\t{$passwd}\tX";
				$outArr = array('id'=>$resm['id'],'name'=>$resm['name'],'passwd'=>$resm['passwd'],'subid'=>'X');
			} else {
				$setStr = "{$resm['firm_id']}\t{$username}\t{$passwd}\t{$resm['id']}";
				$outArr = array('id'=>$resm['firm_id'],'name'=>$resm['name'],'passwd'=>$resm['passwd'],'subid'=>$resm['id']);
			}
			$uStr = self::authcode($setStr,"ENCODE",self::$loginKey);
			setcookie(self::$adminLoginCookieName, $uStr,$life, '/');
			return $outArr;
		}
		return false;

	}

	public static function checkAvatar($uid){
		return uc_check_avatar($uid);
	}


	public static function getEScoreField($eid){
		if(empty($eid)){
			return false;
		}

		$db = Db_Resume::instance();
		$sql = "select * from e_resume_score_set where firm_id=".$eid." order by sort_order desc";
		$list = $db->getAll($sql);

		return $list;
	}

	public static function storeResumeScore(array $param){
		$uid = !empty($param['uid']) ? $param['uid'] : 0;
		$eid = !empty($param['eid']) ? $param['eid'] : 0;
		$detail = !empty($param['detail']) ? $param['detail'] : '';
		$total = !empty($param['total']) ? $param['total'] : 0;
		$commit = !empty($param['commit']) ? $param['commit'] : '';

		if($uid == 0 || $eid == 0 || $detail == '' || $total == 0){
			return false;
		}

		$db = Db_Resume::instance();
		$sql = "select id from e_resume_score where uid={$uid} and eid={$eid} limit 1";
		$id = $db->getOne($sql);

		if(!$id){
			$insert_sql = "insert into e_resume_score(uid, eid, jobid, detail, total, commit) values ({$uid}, $eid, 0, '{$detail}', $total, '{$commit}')";
			$re = $db->query($insert_sql);

			return $re;
		}

		return false;
	}

	public static function getResumeScore(array $param){
		$uid = !empty($param['uid']) ? $param['uid'] : 0;
		$eid = !empty($param['eid']) ? $param['eid'] : 0;

		if($uid ==0 || $eid ==0){
			return false;
		}

		$db = Db_Resume::instance();
		$sql = "select detail, total, commit from e_resume_score where uid={$uid} and eid={$eid} limit 1";
		$info = $db->getRow($sql);

		return $info;
	}

	/**
	 * get one user section arr
	 * $userInfo[0] firmid
	 * $userInfo[1] name
	 * $userInfo[2] passwd
	 * $userInfo[3] subid
	 * @param array $userInfo
	 * @return array
	 */
	public static function getUserSection(array $userInfo)
	{
		if(!$userInfo) return '';
		$outArr = '';

		$db = Db_Resume::instance();
		if($userInfo[3]){
			if('X' == $userInfo[3]){ //manager
				$sql = "Select id,name From `e_section` Where firm_id='{$userInfo[0]}' and status=0 ";
				$data = $db->getAll($sql);
				if($data){
					foreach ($data as $val) {
						$outArr[$val['id']] = $val['name'];
					}
				}
			} else { //sub user
				$sectionId = $db->getOne("Select section_id From `e_sub_user` Where id='{$userInfo[3]}' and status=0");
				if($sectionId){
					$sql = "Select id,name From `e_section` Where firm_id='{$userInfo[0]}' and status=0 and id='{$sectionId}' ";
					$data = $db->getRow($sql);
					if($data){
						$outArr[$data['id']] = $val['name'];
					}
				}
			}
		}

		return $outArr;
	}


	public static function AddEPlace(array $param){
		$eid = !empty($param['eid']) ? $param['eid'] : 0;
		$name = !empty($param['name']) ? $param['name'] : '';
		if($eid == 0 || empty($name)){
			return false;
		}

		$db = Db_Resume::instance();

		$sql = "insert into  e_place_list(eid, name) values ($eid, '{$name}')";
		$re = $db->query($sql);

		return $re;
	}

	public static function GetEPlace(array $param){
		$eid = !empty($param['eid']) ? $param['eid'] : 0;
		if($eid == 0){
			return false;
		}

		$db = Db_Resume::instance();

		$options = array(
				'db'        => $db,
				'cols'      => 'id, name', #取得列
				'fromSql'   => 'from e_place_list', #from部分的语句
				'whereSql'  => 'where eid='.$eid, #where部分的语句
				'onlyData'  => false, #只获得数据
				'debug'     => false,
				);
		$list = Libs_DBHelper::getList($options);

		return $list;
	}
}

?>
